﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace IceTea.Domain.Models
{
    [MetadataType(typeof(ProductMetaData))]
    public partial class Product : IValidatableObject
    {
        public class ProductMetaData
        {
            [Required(ErrorMessage="Please enter product name")]
            [Display(Name="Product Name")]
            [DisplayFormat(ConvertEmptyStringToNull=false)]
            public string Name { get; set; }

            [Display(Name="Product Description")]
            [DisplayFormat(ConvertEmptyStringToNull=false)]
            public string Description { get; set; }

            [Display(Name="Product Vision")]
            [DisplayFormat(ConvertEmptyStringToNull=false)]
            public string Vision { get; set; }

            [Display(Name="Sprint Duration")]
            [Range(1, 8, ErrorMessage="Sprint duration should be between 1 ~ 8 weeks")]
            public int SprintDuration { get; set; }
        }

        #region Implements of IValidatableObject
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            List<ValidationResult> errors = new List<ValidationResult>();
            if (!IsProjectNameUnique(this.Name))
            {
                errors.Add(new ValidationResult("The product name is already exist"));
            }
            return errors;
        }
        #endregion

        public bool IsProjectNameUnique(string productName)
        {
            using (IceTeaEntities ite = new IceTeaEntities())
            {
                if (this.Id > 0)
                {
                    if (ite.Products.Any(p => p.Id != this.Id && p.Name == this.Name))
                        return false;
                }
                else
                {
                    if (ite.Products.Any(p => p.Name == this.Name))
                        return false;
                }
            }
            return true;
        }

        public void CopyFrom(Product product)
        {
            this.Name = product.Name;
            this.Description = product.Description;
            this.SprintDuration = product.SprintDuration;
            this.Vision = product.Vision;
        }
    }
}
